package com.websocket.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by simon on 5/21/17.
 */
@WebListener
public class RequestListener implements ServletRequestListener {
    private static Logger logger = LoggerFactory.getLogger(RequestListener.class);

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        //不然 web socket 获取不到httpSession
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        if (request == null) {
            return;
        }
        HttpSession httpSession = request.getSession();
        if (httpSession == null) {
            return;
        }
        logger.info("X-Sessio-Id :{} init", httpSession.getId());
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        if (request == null) {
            return;
        }
        HttpSession httpSession = request.getSession();
        if (httpSession == null) {
            return;
        }
        logger.info("X-Sessio-Id :{} destroyed", httpSession.getId());

    }

}